﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;


namespace BackEnd.Common
{
    /// <summary>
    /// Lớp thuộc tính check ủy quyền của người dùng. Kế thừa từ lớp AuthorizeAttribute
    /// </summary>
    public class CustomAuthorizeAttribute : AuthorizeAttribute
    {
        //public bool IsMenu;
        /// <summary>
        /// Thông tin Action cần check phân quyền
        /// </summary>
        public string Action { get; set; }
        private bool _HasPermission = false;
        private bool _IsLogged = false;

        protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            
            var user = (string)httpContext.Session[Common.Constants.SessionKeys.UserInfo];
            var permissionActions = (string)httpContext.Session[Common.Constants.SessionKeys.PermissionActions];
            if (String.IsNullOrEmpty(user))
            {
                _IsLogged = false;

            }
            else
            {
                _IsLogged = true;

                //Neu yeu cau check accion
                if ((!String.IsNullOrEmpty(Action)))
                {
                    _HasPermission = permissionActions != null && permissionActions.Contains(Action);
                    return _HasPermission;
                }
                else
                {
                    return true;
                }

            }            
            return false;
        }
        protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
        {
            if (_IsLogged == false)
            {
                filterContext.Result = new RedirectToRouteResult(
                                   new RouteValueDictionary 
                                   {
                                       { "action", "Login" },
                                       { "controller", "Account" },
                                       { "returnUrl", filterContext.HttpContext.Request.RawUrl }
                                   });
            }
            else
            {
                if (_HasPermission == false)
                {

                    filterContext.Result = new RedirectToRouteResult(
                                           new RouteValueDictionary 
                                   {
                                       { "action", "UnAuthorized" },
                                       { "controller", "ErrorsHandler" }
                                   });
                }
                else
                {

                }
            }

        }

    }   
}